(function($)
{
    $.GetFilterDataForRequest = function(filter)
    {
        var result = {};
        for(var i = 0; i < filter.length; i++)
        {
            result['filter' + i.toString() + 'field'] = filter[i].fieldName;
            result['filter' + i.toString() + 'value'] = filter[i].value;
            result['filter' + i.toString() + 'operator'] = filter[i].operator;
        }
        return result;
    };

    $.fn.pguiGridView = function(aSettings)
    {
        this.each(function()
        {
            $(this).attr('has-pg-grid-view', 'true');
            var data = {
                filter: [],
                selectableRows: false
            };
            $(this).data("pg-grid-view", data);
        });
    };

    $.fn.pguiGridViewRow = function(aSettings)
    {
        this.each(function()
        {
            $(this).attr('has-pg-grid-view-row', 'true');

            var data = {};
            $(this).SetRowData(data);

            $(this).find('a').click(function(event)
            {
                event.stopPropagation();
            });

            $(this).click(function(event)
            {
                $(this).trigger('onSelect.GridRow');
            });
        });
    };

    $.fn.GetGridView = function()
    {
        var row = this.FilterRows().first();
        return row.closest('*[has-pg-grid-view=true]');
    };
    
    $.fn.FilterRows = function()
    {
        return this.filter('*');
    };

    $.fn.GetPrimaryKeys = function()
    {
        var row = this.filter('*[has-pg-grid-view-row=true]').first();
        
        var pkIndex = 1;
        var result = [];
        if (row.attr('pk-value-' + pkIndex))
        {
            result.push(row.attr('pk-value-' + pkIndex));
            pkIndex++;
        }
        
        return result;
    };

    $.fn.GetRowData = function()
    {
        return $(this).data("pg-grid-view-row");
    };

    $.fn.SetRowData = function(data)
    {
        $(this).data("pg-grid-view-row", data);
    };

    $.fn.pguiGridViewCell = function(aSettings)
    {
        this.each(function()
        {
            $(this).attr('has-pg-grid-view-cell', 'true');
        });
    };

    $.fn.GetData = function()
    {
        if (this.is('[has-pg-grid-view=true]'))
            return $(this).data("pg-grid-view");
    };

    $.fn.SetData = function(data)
    {
        if (this.is('[has-pg-grid-view=true]'))
            $(this).data("pg-grid-view", data);
    };

    $.fn.SetDataFilter = function(dataFilter)
    {
        this.filter('*[has-pg-grid-view=true]').each(function()
        {
            var data = $(this).data("pg-grid-view");
            data.filter = dataFilter;
            $(this).data("pg-grid-view", data);
        });
    };

    $.fn.RefreshData = function()
    {
        this.filter('*[has-pg-grid-view=true]').each(function()
        {
            var grid = $(this);
            var dataUrl = grid.attr('data-url');
            var data = $(this).data('pg-grid-view');
            
            var requestData =
                {
                    'q': 'refresh'
                };
            
            $.get(
                dataUrl,
                $.extend({}, requestData, $.GetFilterDataForRequest(data.filter)),
                function(data, textStatus, xnr)
                {
                    var responseXml = $(data).find('response');
                    //alert(responseXml.find('type').text());
                    //alert(responseXml.find('rows').text());
                    
                    grid.ClearRows();
                    grid.AppendRows(responseXml.find('rows').text());
                },
                'xml'
            );
        });
    };

    $.fn.ClearRows = function()
    {
        this.filter('*[has-pg-grid-view=true]').each(function()
        {
            var grid = $(this);
            grid.find('.pgui-grid-view-row-container').find('.pgui-grid-view-row').remove();
        });
    };

    $.fn.AppendRows = function(rowsAsText)
    {
        this.filter('*[has-pg-grid-view=true]').each(function()
        {
            var grid = $(this);
            var rows = $(rowsAsText);
            grid.find('.pgui-grid-view-row-container').append(rows);
            rows.ProcessUnobtrusive();

            rows.bind('onSelect.GridRow', function()
            {
                OnSelectGridRow(grid, $(this));

            })
        });
    };

    function OnSelectGridRow(grid, row)
    {
        var data = grid.GetData();
        if (data.selectableRows)
        {
            grid.GetRows().removeClass('selected');
            row.addClass('selected');
            grid.trigger('onSelectRow.Grid', [row]);
        }
    }

    $.fn.OnSelectRow = function(eventHandler)
    {
        this.filter('*[has-pg-grid-view=true]').each(function()
        {
            var grid = $(this);
            grid.bind('onSelectRow.Grid', eventHandler);
        });
    };

    $.fn.FilterGrids = function()
    {
        return this.filter('*[has-pg-grid-view=true]');
    };

    $.fn.GetRows = function()
    {
        var grid = this.FilterGrids().first();
        return grid.find('.pgui-grid-view-row-container').children().FilterRows();
    };

    $.fn.SetSelectableRows = function(value)
    {
        this.FilterGrids().each(function()
        {
            var data = $(this).GetData();
            data.selectableRows = value;
            $(this).SetData(data);
        });
    };
    
})(jQuery);

